package com.gambi.example.tapestry.services;

import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Method;

import org.apache.tapestry5.services.ComponentEventResultProcessor;
import org.apache.tapestry5.services.RequestGlobals;

import com.google.gwt.user.client.rpc.SerializationException;
import com.google.gwt.user.server.rpc.RPC;

public class GWTComponentEventResultProcessor implements
		ComponentEventResultProcessor {

	private final RequestGlobals requestGlobals;

	public GWTComponentEventResultProcessor(RequestGlobals requestGlobals) {
		this.requestGlobals = requestGlobals;
	}

	public void processResultValue(Object value) throws IOException {
		System.out.println("GwtComponentEventResultProcessor.processResultValue() value " + value);

		// Is this a Default for GWT ?
		OutputStream os = requestGlobals.getResponse().getOutputStream("UTF-8");
		try {
			os.write(
					RPC.encodeResponseForSuccess(
							(Method) requestGlobals.getRequest().getAttribute("method"), value).getBytes());
		} catch (SerializationException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		} finally {
			if (os != null) {
				os.close();
			}
		}
	}
}
